<script setup>
import { ref, onMounted } from 'vue'
import { usetikuUserStore } from '@/stores/sj-user'
import request from '@/utils/sj-request'
import * as echarts from 'echarts'
import katex from 'katex'
import 'katex/dist/katex.min.css'

const userStore = usetikuUserStore()
const userInfo = ref(userStore.userInfo)

// 统计数据
const stats = ref({
  totalQuestions: 0,
  totalSubjects: 0,
  totalPapers: 0,
  recentActivity: 0
})

// 最近活动列表
const activities = ref([])

// 学科试题统计数据
const subjectData = ref([])

// 题型试题统计数据
const typeData = ref([])

// 图表实例引用
const subjectChartRef = ref(null)
const typeChartRef = ref(null)
let subjectChart = null
let typeChart = null

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const res = await request.get('/dashboard/statistics')
    if (res.code === 200) {
      stats.value = res.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取最近活动
const fetchRecentActivities = async () => {
  try {
    const res = await request.get('/dashboard/recent-activities')
    if (res.code === 200) {
      activities.value = res.data
    }
  } catch (error) {
    console.error('获取最近活动失败:', error)
  }
}

// 获取学科试题统计
const fetchSubjectData = async () => {
  try {
    const res = await request.get('/dashboard/question-count-by-subject')
    if (res.code === 200) {
      subjectData.value = res.data
      initSubjectChart()
    }
  } catch (error) {
    console.error('获取学科试题统计失败:', error)
  }
}

// 获取题型试题统计
const fetchTypeData = async () => {
  try {
    const res = await request.get('/dashboard/question-count-by-type')
    if (res.code === 200) {
      typeData.value = res.data
      initTypeChart()
    }
  } catch (error) {
    console.error('获取题型试题统计失败:', error)
  }
}

// 初始化学科试题统计图表
const initSubjectChart = () => {
  if (!subjectChartRef.value) return
  
  // 销毁旧图表实例
  if (subjectChart) {
    subjectChart.dispose()
  }
  
  // 创建新图表实例
  subjectChart = echarts.init(subjectChartRef.value)
  
  // 准备数据
  const subjectNames = subjectData.value.map(item => item.subjectName)
  const subjectCounts = subjectData.value.map(item => item.count)
  
  // 配置图表选项
  const option = {
    title: {
      text: '各学科试题数量统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: subjectNames,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '试题数量',
        type: 'bar',
        data: subjectCounts,
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  // 设置图表选项并渲染
  subjectChart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    subjectChart.resize()
  })
}

// 初始化题型试题统计图表
const initTypeChart = () => {
  if (!typeChartRef.value) return
  
  // 销毁旧图表实例
  if (typeChart) {
    typeChart.dispose()
  }
  
  // 创建新图表实例
  typeChart = echarts.init(typeChartRef.value)
  
  // 准备数据
  const pieData = typeData.value.map(item => ({
    name: item.typeName,
    value: item.count
  }))
  
  // 配置图表选项
  const option = {
    title: {
      text: '各题型试题数量占比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: pieData.map(item => item.name)
    },
    series: [
      {
        name: '题型分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  }
  
  // 设置图表选项并渲染
  typeChart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    typeChart.resize()
  })
}

// 渲染数学公式
const renderMathFormula = (content) => {
  if (!content) return ''
  
  // 使用正则表达式匹配KaTeX公式
  const regex = /\$\$(.*?)\$\$/g
  
  // 替换所有匹配的公式
  return content.replace(regex, (match, formula) => {
    try {
      // 使用KaTeX渲染公式
      return katex.renderToString(formula, {
        throwOnError: false,
        displayMode: false
      })
    } catch (error) {
      console.error('KaTeX渲染错误:', error)
      return match
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStatistics()
  fetchRecentActivities()
  fetchSubjectData()
  fetchTypeData()
})
</script>

<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 欢迎卡片 -->
      <el-col :span="24">
        <el-card class="welcome-card" shadow="hover">
          <div class="welcome-info">
            <h2>欢迎回来，{{ userInfo?.account || '用户' }}</h2>
            <p>今天是 {{ new Date().toLocaleDateString() }}，祝您使用愉快！</p>
          </div>
        </el-card>
      </el-col>
      
      <!-- 学科卡片区域 - 仅对教师和学科组长显示 -->
      <el-col :span="24" v-if="userInfo?.roleId !== 1 && userInfo?.subjects && userInfo.subjects.length > 0">
        <el-card shadow="hover" class="subject-card-container">
          <template #header>
            <div class="card-header">
              <span>我的学科</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="subject in userInfo.subjects" :key="subject.id" class="subject-item">
              <el-card shadow="hover" class="subject-card">
                <div class="subject-icon">
                  <el-icon><Reading /></el-icon>
                </div>
                <div class="subject-info">
                  <div class="subject-name">{{ subject.name }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      
      <!-- 统计卡片 -->
      <el-col :xs="24" :sm="12" :md="6" class="stat-item">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon" style="background-color: #409EFF;">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-title">试题总数</div>
            <div class="stat-value">{{ stats.totalQuestions }}</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" class="stat-item">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon" style="background-color: #67C23A;">
            <el-icon><Collection /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-title">学科数量</div>
            <div class="stat-value">{{ stats.totalSubjects }}</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" class="stat-item">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon" style="background-color: #E6A23C;">
            <el-icon><Files /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-title">试卷数量</div>
            <div class="stat-value">{{ stats.totalPapers }}</div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" class="stat-item">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon" style="background-color: #F56C6C;">
            <el-icon><Timer /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-title">近期活动</div>
            <div class="stat-value">{{ stats.recentActivity }}</div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 最近活动 -->
      <el-col :span="24" :lg="12">
        <el-card class="recent-activity" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近活动</span>
            </div>
          </template>
          <el-table :data="activities" style="width: 100%" v-loading="activities.length === 0">
            <el-table-column prop="type" label="类型" width="100" />
            <el-table-column label="内容" min-width="200">
              <template #default="{row}">
                <div v-html="renderMathFormula(row.content)"></div>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="时间" width="180" />
          </el-table>
        </el-card>
      </el-col>
      
      <!-- 学科试题统计图表 -->
      <el-col :span="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>学科试题统计</span>
            </div>
          </template>
          <div ref="subjectChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 题型试题统计图表 -->
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>题型试题统计</span>
            </div>
          </template>
          <div ref="typeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 20px 0;
}

.welcome-card {
  margin-bottom: 20px;
  background: linear-gradient(to right, #1890ff, #36cfc9);
  color: white;
}

.welcome-info {
  padding: 10px;
}

.welcome-info h2 {
  margin-top: 0;
}

.stat-item {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  height: 120px;
  padding: 15px;
}

.stat-icon {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
  color: white;
  font-size: 24px;
}

.stat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-title {
  font-size: 16px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1.2;
}

.recent-activity, .chart-card, .subject-card-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.subject-item {
  margin-bottom: 15px;
}

.subject-card {
  display: flex;
  align-items: center;
  padding: 15px;
  transition: all 0.3s;
}

.subject-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.subject-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #67C23A;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
  color: white;
  font-size: 20px;
}

.subject-info {
  flex: 1;
}

.subject-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
</style>